package com.tom.controller;

import com.tom.config.JwtProperties;
import com.tom.entity.Result;
import com.tom.entity.StatusCode;
import com.tom.model.Account;
import com.tom.model.User;
import com.tom.model.dto.UserInfo;
import com.tom.model.dto.UserInfoDto;
import com.tom.service.AccountService;
import com.tom.service.UserService;
import com.tom.utils.CookieUtils;
import com.tom.utils.JwtUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api")
public class Apis {

    @Autowired
    private UserService userService;

    @Autowired
    private AccountService accountService;

    @Autowired
    private JwtProperties properties;

    @RequestMapping(path = "/test2")
    public Result test(Account account){
        return new Result( StatusCode.OK,"请求成功");
    }

    @RequestMapping(path = "/test-log")
    public Result log(){
        // TRACE < DEBUG < INFO < WARN < ERROR < FATAL。
        log.trace("日志输出：trace");
        log.debug("日志输出：debug");
        log.info("日志输出：info");
        log.warn("日志输出：warn");
        log.error("日志输出：error");
        return new Result( StatusCode.OK,"请求成功");
    }

    @RequestMapping("/user-list")
    public Result getUserList(){
        return new Result(StatusCode.OK,"请求成功",userService.findAll());
    }

    @RequestMapping(path = "/user-select", method= RequestMethod.POST)
    public Result getUserById(@RequestParam(value = "id", required = false) Long id){
        return new Result( StatusCode.OK,"请求成功",userService.findById(id));
    }

    @RequestMapping(path = "/user-select2", method= RequestMethod.POST)
    public Result getUserById2(User user){
        return new Result( StatusCode.OK,"请求成功",userService.findById(user.getId()));
    }

    @RequestMapping(path = "/login", method= RequestMethod.POST)
    public Result login(User user){
        if (user.getUsername() == null) {
            return new Result(StatusCode.ERROR,"账号为空");
        }
        if (user.getPassword() == null) {
            return new Result(StatusCode.ERROR,"密码为空");
        }
        Long uid = userService.login(user);
        if (uid != null) {
            return new Result(StatusCode.OK,"请求成功",uid);
        }
        return new Result( StatusCode.ERROR,"账号或者密码错误");
    }

    @RequestMapping(path = "/user-info", method= RequestMethod.POST)
    public Result getUserInfo(@RequestParam(value = "id", required = false) Long id){
        if (id == null) {
            return new Result(StatusCode.ERROR,"参数为空");
        }
        UserInfoDto userInfoDto = userService.getUserInfo(id);
        if (userInfoDto != null) {
            return new Result(StatusCode.OK,"请求成功",userInfoDto);
        }
        return new Result( StatusCode.ERROR,"参数错误");
    }


    @RequestMapping(path = "/accredit", method= RequestMethod.POST)
    public Result accredit(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            HttpServletRequest request,
            HttpServletResponse response
    ){
        //1.登录校验
        String token = this.userService.authentication(username,password);
        if (StringUtils.isBlank(token)){
            return new Result( StatusCode.ERROR,"参数错误");
        }
        System.out.println(token);
        //2.将token写入cookie，并指定httpOnly为true，防止通过js获取和修改
        CookieUtils.setCookie(request,response,properties.getCookieName(),token,properties.getCookieMaxAge(),true);

        return new Result(StatusCode.OK,"请求成功");
    }

    /**
     * 用户验证
     * @param token
     * @return
     */
    @GetMapping("verify")
    public Result verifyUser(@CookieValue("LY_TOKEN") String token,HttpServletRequest request,
                                               HttpServletResponse response){
        try{
            //1.从token中解析token信息
            UserInfo userInfo = JwtUtils.getInfoFromToken(token,this.properties.getPublicKey());
            //2.解析成功要重新刷新token
            token = JwtUtils.generateToken(userInfo,this.properties.getPrivateKey(),this.properties.getExpire());
            //3.更新Cookie中的token
            CookieUtils.setCookie(request,response,this.properties.getCookieName(),token,this.properties.getCookieMaxAge());
            //4.解析成功返回用户信息
            return new Result(StatusCode.OK,"请求成功",userInfo);
        }catch (Exception e){
            e.printStackTrace();
        }
        //5.出现异常,相应401
        return new Result( StatusCode.ERROR,"参数错误");
    }
}
